package com.socialrss.viewlisteners;

import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import com.socialrss.R;
import com.socialrss.constants.SocialNetworkNames;
import com.socialrss.constants.SocialNetworkNames.SocialNetKeys;
import com.socialrss.instagramkit.InstagramConstants;
import com.socialrss.instagramkit.InstagramUtils;
import com.socialrss.utils.SocialRssModel;
import com.socialrss.utils.foursquarekit.FoursquareUtils;
import com.socialrss.utils.twitter.TwitterFriendsThread;
import com.socialrss.utils.twitter.TwitterUtil;
import com.socialrss.accounts.AccountOwner;
import com.socialrss.accounts.InstagramUser;
import com.socialrss.adapters.SocialNetworkAdapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class AddConnectionFromSocialNetwork extends BaseActivity {

	//VAR
	ArrayList <String> networkList;
	ArrayList <String> mIcons; 
	ListView networkListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		setContentView(R.layout.manage_social_networks);
		

		networkList = new ArrayList<String>(4);
		mIcons = new ArrayList <String>(4);
		networkListView = (ListView)findViewById(R.id.msn_networkList);

		networkList.add("Facebook");
		networkList.add("Twitter");
		networkList.add("Google+");
		networkList.add("Instagram");
		
		registerForContextMenu(networkListView);
	    // Instead of using a regular ArrayAdapter to pull Strings from an array,
	    // we will create a custom ArrayAdapter below. This bit of code sets the adapter
	    // of our ListView, lv, to our customer adapter.
		SocialNetworkAdapter adapter = new SocialNetworkAdapter(this, networkList);
	   networkListView.setAdapter(adapter);

	   networkListView.setOnItemClickListener(new OnItemClickListener() {
		   @Override
		   public void onItemClick(AdapterView<?> parent, View view,
				   int position, long id) {
			   Intent intent = null;
			   Bundle bun = new Bundle();
			   
			   if(position == 0) {
				   intent = new Intent(AddConnectionFromSocialNetwork.this,ConnectionsOfSelectedSocialNetwork.class);
				   bun.putString("socialnetwork", SocialNetworkNames.FACEBOOK);
				   intent.putExtras(bun);
			   } else if(position == 1) {
				   twitterAccountCheck();
				   intent = new Intent(AddConnectionFromSocialNetwork.this,ConnectionsOfSelectedSocialNetwork.class);
				   bun.putString("socialnetwork", SocialNetworkNames.TWITTER);
				   intent.putExtras(bun);
			   } else if(position == 2) {
				   intent = new Intent(AddConnectionFromSocialNetwork.this,ConnectionsOfSelectedSocialNetwork.class);
				   foursquareAccountCheck();
				   bun.putString("socialnetwork", SocialNetworkNames.FOURSQUARE);
				   intent.putExtras(bun);
				   startActivity(intent);
			   } else if(position == 3) {
				   instagramAccountCheck();
				   intent = new Intent(AddConnectionFromSocialNetwork.this,ConnectionsOfSelectedSocialNetwork.class);
				   bun.putString("socialnetwork", SocialNetworkNames.INSTAGRAM);
				   intent.putExtras(bun);
				   startActivity(intent);
			   }
			     
		   }

	   });
	}
	/**
	 * Control whether Twitter account is authenticated or not. If it is, then fetch friends
	 * @return false if there is no account, true otherwise
	 */
	private boolean twitterAccountCheck(){
		if(TwitterUtil.isTwitterLoggedInAlready()){
			TwitterFriendsThread th = new TwitterFriendsThread();
			th.execute();
			try {
				th.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			return true;
		}
		return false;
	}
	/**
	 * Control whether Foursquare account is authenticated or not. If it is, then fetch friends
	 * @return false if there is no account, true otherwise
	 */
	private boolean foursquareAccountCheck(){
		AccountOwner owner = SocialRssModel.Instance(null).getAccessTokenOfSocialNet(SocialNetKeys.f_sq.toString());
		if(!owner.isValid()){
			Log.e(InstagramConstants.LOG_ERROR, "Instagram account couldn't be found!");
			return false;
		}
		FoursquareUtils.Instance().getFriends();
		return true;
	}
	/**
	 * Control whether Instagram account is authenticated or not. If it is, then fetch friends
	 * @return false if there is no account, true otherwise
	 */
	private boolean  instagramAccountCheck(){
		AccountOwner owner = SocialRssModel.Instance(null).getAccessTokenOfSocialNet(SocialNetKeys.ins.toString());
		if(!owner.isValid()){
			Log.e(InstagramConstants.LOG_ERROR, "Instagram account couldn't be found!");
			return false;
		}
		int numOfinstagramUsersInDB = 0;
		InstagramUser temp = new InstagramUser(Integer.parseInt(owner.getUserId()), "Owner");
		temp = InstagramUtils.Instance().getUserInfo(temp.getId());
		//first control howmany of them are in
		//set instagramUserInDB
		numOfinstagramUsersInDB = SocialRssModel.Instance(null).getNumOfTuplesInTableOfSocialNetwork(SocialNetworkNames.SocialNetKeys.ins);
		//temp.setId(-1);
		InstagramUser[] follows_list = InstagramUtils.Instance().get_Ids_Of_AllFollows(temp, temp.getFollows() - numOfinstagramUsersInDB);			//retrieve info of all follows
		if(follows_list.length > 0){
			SocialRssModel.Instance(null).insertListOfConnections(follows_list, SocialNetworkNames.SocialNetKeys.ins);
		}
		Log.i(InstagramConstants.LOG_INFO, follows_list.length + " new instagram connections has been inserted.");
		return true;
	}
}
